package com.biao.cloud.controller;

import com.biao.cloud.entities.Payment;
import com.biao.cloud.entities.Result;
import com.biao.cloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    // 注意是org.springframework.cloud.client.discovery.DiscoveryClient; 包下面的
    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();      // 获取所有服务名称
        services.forEach(element -> log.info("包含服务:" + element));
        // 获取CLOUD-PAYMENT-SERVICE 服务的信息
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(instance -> {
            log.info(instance.getInstanceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        });
        return discoveryClient;
    }

    @PostMapping("/payment/create")
    public Result<Payment> create(@RequestBody Payment payment) {
        int i = paymentService.create(payment);
        log.info("插入结果" + i);
        if (i > 0) {
            return new Result(200, "在" + serverPort + "插入成功", i);
        } else {
            return new Result(444, "在" + serverPort + "插入失败");
        }
    }

    @GetMapping("/payment/get/{id}")
    public Result<Payment> getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("查询" + payment);
        return new Result(200, "在" + serverPort + "查询成功了, id:" + id, payment);
    }

    @GetMapping(value = "/payment/lb")
    public String getPaymentLB() {
        return serverPort;
    }

    @GetMapping("/payment/zipkin")
    public String paymentZipkin() {
        return "hi ,i'am paymentzipkin server fall back，welcome to atguigu，O(∩_∩)O哈哈~";
    }
}
